﻿using System.Reflection;
using System.Reflection.Emit;

namespace Dynamic.Api.Utils
{
    public class DynamicAssembly
    {

        AssemblyBuilder _assemblyBuilder;
        ModuleBuilder _moduleBuilder;
        string _guid = Guid.NewGuid().ToString("N").ToUpper();
        public AssemblyBuilder AssemblyBuilder
        {
            get
            {
                EnsureAssemblyBuilder();
                return _assemblyBuilder;
            }
        }

        public ModuleBuilder ModuleBuilder
        {
            get
            {
                EnsureModuleBuilder();
                return _moduleBuilder;
            }
        }

        void EnsureAssemblyBuilder()
        {
            if (_assemblyBuilder == null)
            {
                _assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(_guid), AssemblyBuilderAccess.Run);
            }
        }

        void EnsureModuleBuilder()
        {
            EnsureAssemblyBuilder();
            if (_moduleBuilder == null)
            {
                _moduleBuilder = _assemblyBuilder.DefineDynamicModule("MainModule");
            }
        }


    }
}
